package com.feng.chat.controller;


import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.feng.chat.common.Common;
import com.feng.chat.dto.ContentDTO;
import com.feng.chat.dto.KeepAlive;
import com.feng.chat.entity.TalkRecords;
import com.feng.chat.entity.Users;
import com.feng.chat.service.ITalkRecordsService;
import com.feng.chat.service.IUsersService;
import com.feng.chat.service.impl.TalkRecordsServiceImpl;
import com.feng.chat.service.impl.UsersServiceImpl;
import com.feng.chat.utils.GetUserUtil;
import com.feng.chat.vo.EventTalkDataVO;
import com.feng.chat.vo.EventTalkVO;
import com.feng.chat.vo.Ping;
import com.feng.chat.ws.GetHttpServletRequestConfigurator;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpSession;
import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

@Component
@ServerEndpoint(value = "/wss/default.io", configurator = GetHttpServletRequestConfigurator.class)
public class WebSocketSever {


    public static Map<Integer, WebSocketSever> onLine = new ConcurrentHashMap<>();
    static {

    }

    private Session session;

    public Session getSession() {
        return session;
    }

    private Integer id;

    @OnOpen
    public void onOpen(Session session, EndpointConfig config) {
        System.out.println("连接成功");

        this.session = session;
        this.id = (Integer) config.getUserProperties().get("id");

        onLine.put(this.id, this);

        KeepAlive keepAlive = new KeepAlive();
        keepAlive.setContent(new Ping(20, 60));
        keepAlive.setEvent(Common.CONNECT);
        try {
            session.getBasicRemote().sendText(JSON.toJSONString(keepAlive));
        } catch (IOException e) {
            e.printStackTrace();
        }

        KeepAlive loginKeepAlive = new KeepAlive();
        loginKeepAlive.setEvent(Common.EVENT_LOGIN);

        Map<String, Integer> map = new HashMap<>();
        map.put("user_id",this.id);
        map.put("status",1);
        loginKeepAlive.setContent(map);

        List<Integer> receiver_ids = new ArrayList<>(onLine.keySet());
        receiver_ids.remove(this.id);
        GetUserUtil.sendManyMessage(loginKeepAlive,receiver_ids);

    }

    //接收到消息后触发
    @OnMessage
    public void onMessage(String message, Session session) {
        KeepAlive msg = JSON.parseObject(message, KeepAlive.class);

        if (Common.HEARTBEAT.equals(msg.getEvent())) { //心跳检测
            KeepAlive keepAlive = new KeepAlive();
            keepAlive.setContent("pong");
            keepAlive.setEvent(Common.HEARTBEAT);
            try {
                session.getBasicRemote().sendText(JSON.toJSONString(keepAlive));
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        //消息撤回事件
        /*QueryWrapper<TalkRecords> revokeQueryWrapper = new QueryWrapper<>();
        revokeQueryWrapper.eq("receiver_id",this.id).ne("msg_type",7).eq("is_revoke",1);
        List<TalkRecords> revokeList = talkRecordsService.list(revokeQueryWrapper);
        if (revokeList.size()>0){
            KeepAlive keepAlive = new KeepAlive();
            keepAlive.setEvent(Common.EVENT_TALK_REVOKE);

        }*/


    }

    @OnClose
    public void onClose(Session session) {
        System.out.println("连接已关闭");
        onLine.remove(this.id);

        KeepAlive loginKeepAlive = new KeepAlive();
        loginKeepAlive.setEvent(Common.EVENT_LOGIN);

        Map<String, Integer> map = new HashMap<>();
        map.put("user_id",this.id);
        map.put("status",0);
        loginKeepAlive.setContent(map);

        List<Integer> receiver_ids = new ArrayList<>(onLine.keySet());
        receiver_ids.remove(this.id);
        GetUserUtil.sendManyMessage(loginKeepAlive,receiver_ids);
    }

    @OnError
    public void error(Session session, Throwable t) {
        System.err.println(t.getCause());
    }
}
